package jehc.cloud.gen.service.generator;

import jehc.cloud.common.util.ExceptionUtil;
import jehc.cloud.gen.model.XtGenerator;
import jehc.cloud.gen.model.XtGeneratorTableColumn;
import jehc.cloud.gen.model.XtGeneratorTableManyToOne;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
 * @Desc 生成控制层代码
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Slf4j
public class GeneratorWeb extends GeneratorUtil {
	/**
	 * 创建控制层(Web)
	 * @param xtGeneratorTableColumnList
	 * @param xtGenerator
	 */
	 public String createWeb(List<XtGeneratorTableColumn> xtGeneratorTableColumnList, XtGenerator xtGenerator){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	StringBuffer sb = new StringBuffer();
    	sb.append("package "+xtGenerator.getXt_generator_web_package()+";\r\n");
    	//导入包名
    	sb.append("import java.util.List;\r\n");
    	sb.append("import java.util.HashMap;\r\n");
    	sb.append("import java.util.Map;\r\n");
    	sb.append("import jehc.cloud.common.base.BasePage;\r\n");
    	sb.append("import jehc.cloud.common.base.BaseResult;\r\n");

    	//判断是否为一对多 并且是主表 如果为一对多则导入实体
        if(xtGenerator.getIs_one_to_many().equals("1") && xtGenerator.isIs_main_table()){
        	if(xtGenerator.getOne_to_many_type().equals("0")){
        		sb.append("import xtCore.util.JsonUtil;\r\n");
        	}
        	List<XtGeneratorTableManyToOne> xtGeneratorTableManyToOnes = xtGenerator.getXt_Generator_TableMany_To_OneList();
        	for(int i = 0; i < xtGeneratorTableManyToOnes.size(); i++){
        		XtGeneratorTableManyToOne xtGeneratorTableManyToOne = xtGeneratorTableManyToOnes.get(i);
        		sb.append("import "+ xtGeneratorTableManyToOne.getXt_generator_one_to_many_table_model_package()+"."+toUpperCase(xtGeneratorTableManyToOne.getXt_generator_one_to_many_table_name())+";\r\n");
        		sb.append("import "+ xtGeneratorTableManyToOne.getXt_generator_one_to_many_table_service_package()+"."+toUpperCase(xtGeneratorTableManyToOne.getXt_generator_one_to_many_table_name())+"Service;\r\n");
        	}
        }
    	sb.append("import javax.servlet.http.HttpServletRequest;\r\n");
    	sb.append("import org.springframework.web.bind.annotation.DeleteMapping;\r\n");
    	sb.append("import org.springframework.web.bind.annotation.GetMapping;\r\n");
		sb.append("import org.springframework.web.bind.annotation.PathVariable;\r\n");
		sb.append("import org.springframework.web.bind.annotation.PostMapping;\r\n");
		sb.append("import org.springframework.web.bind.annotation.PutMapping;\r\n");
    	sb.append("import org.springframework.beans.factory.annotation.Autowired;\r\n");
    	sb.append("import org.springframework.web.bind.annotation.RestController;\r\n");
    	sb.append("import org.springframework.web.bind.annotation.RequestMapping;\r\n");
    	sb.append("import org.springframework.web.bind.annotation.RequestMethod;\r\n");
    	sb.append("import org.springframework.web.bind.annotation.*;\r\n");
		sb.append("import jehc.cloud.common.annotation.NeedLoginUnAuth;\r\n");
		sb.append("import jehc.cloud.common.util.StringUtil;\r\n");
		sb.append("import io.swagger.annotations.ApiOperation;\r\n");
    	//是否采用多例模式
    	if("2".equals(xtGenerator.getXt_generator_scope())){
    		sb.append("import org.springframework.context.annotation.Scope;\r\n");
    	}
    	if(xtGenerator.getXt_generator_page().equals("1")){
    		sb.append("import com.github.pagehelper.PageInfo;\r\n");
    	}
    	sb.append("import jehc.cloud.common.base.BaseAction;\r\n");
    	sb.append("import jehc.cloud.common.base.BaseSearch;\r\n");
    	sb.append("import jehc.cloud.common.idgeneration.UUID;\r\n");
    	
    	sb.append("import "+xtGenerator.getXt_generator_model_package()+"."+toUpperCase(xtGenerator.getXt_generator_tbname())+";\r\n");
    	sb.append("import "+xtGenerator.getXt_generator_service_package()+"."+toUpperCase(xtGenerator.getXt_generator_tbname())+"Service;\r\n");
        sb.append("\r\n");
		 //注释部分
		 sb.append("/**\r\n");
		 sb.append("* @Desc "+xtGenerator.getXt_generator_tbcomment()+" \r\n");
		 sb.append("* @Author "+xtGenerator.getXt_userinfo_realName()+"\r\n");
		 sb.append("* @CreateTime "+sdf.format(new Date())+"\r\n");
		 sb.append("*/");
        //Web类模块
        sb.append("\r\n@RestController\r\n");
        sb.append("@RequestMapping(\"/"+lowOneCharAll_(xtGenerator.getXt_generator_tbname())+"\")");
        //是否采用多例模式
    	if("2".equals(xtGenerator.getXt_generator_scope())){
    		sb.append("\r\n@Scope(\"prototype\")");
    	}
        sb.append("\r\npublic class " + toUpperCase(xtGenerator.getXt_generator_tbname())+"Controller" + " extends BaseAction{\r\n");
        //注入Service接口
        sb.append("\t@Autowired\r\n");
        sb.append("\tprivate "+ toUpperCase(xtGenerator.getXt_generator_tbname())+"Service "+lowfristchar(xtGenerator.getXt_generator_tbname())+"Service;\r\n");
        //判断是否为一对多并且是主表 如果为一对多则注解子表接口
        if(xtGenerator.getIs_one_to_many().equals("1") && xtGenerator.isIs_main_table()){
        	List<XtGeneratorTableManyToOne> xtGeneratorTableManyToOnes = xtGenerator.getXt_Generator_TableMany_To_OneList();
        	for(int i = 0; i < xtGeneratorTableManyToOnes.size(); i++){
        		XtGeneratorTableManyToOne xtGeneratorTableManyToOne = xtGeneratorTableManyToOnes.get(i);
        		sb.append("\t@Autowired\r\n");
        		sb.append("\tprivate "+toUpperCase(xtGeneratorTableManyToOne.getXt_generator_one_to_many_table_name())+"Service "+lowfristchar(xtGeneratorTableManyToOne.getXt_generator_one_to_many_table_name())+"Service;\r\n");
        	}
        }
        //WEB中方法
//        //1.1载入初始化页面
//        sb.append(createWebLoadPage(xtGeneratorTableColumnList, xtGenerator));
        //1.2分页
        sb.append(createWebList(xtGeneratorTableColumnList,xtGenerator));
        //1.3查询对象
        sb.append(createWebObj(xtGeneratorTableColumnList,xtGenerator));
        //1.4添加
        sb.append(createWebAdd(xtGeneratorTableColumnList,xtGenerator));
        //1.5修改
        sb.append(createWebUpdate(xtGeneratorTableColumnList,xtGenerator));
        //1.6删除
        sb.append(createWebDel(xtGeneratorTableColumnList,xtGenerator));
//        //1.7复制一行并生成记录
//        sb.append(createWebCopy(xtGeneratorTableColumnList, xtGenerator));
//        //1.8导出
//        sb.append(createExport(xtGeneratorTableColumnList, xtGenerator));
        
        if("1".equals(xtGenerator.getKf_mode())){
        	//1.9发送到新增页面（bootstrap风格方式开发）
//        	sb.append(createToAdd(xtGeneratorTableColumnList, xt_Generator));
//            //2.0发送到编辑页面（bootstrap风格方式开发）
//        	sb.append(createToUpdate(xtGeneratorTableColumnList, xt_Generator));
//            //2.1发送到明细页面（bootstrap风格方式开发）
//        	sb.append(createToDetail(xtGeneratorTableColumnList, xt_Generator));
        }
        sb.append("}\r\n");
        String path = xtGenerator.getXt_generator_path();
		OutputStreamWriter out = null;
		try {
			out = new OutputStreamWriter(new FileOutputStream(path+toUpperCase(xtGenerator.getXt_generator_tbname()) + "Controller.java"),"UTF-8");
			try {
				out.write(sb.toString());
			} catch (IOException e) {
				log.error(e.getMessage());
				throw new ExceptionUtil(e.getMessage(),e.getCause());
			}
		} catch (UnsupportedEncodingException e) {
			log.error(e.getMessage());
			throw new ExceptionUtil(e.getMessage(),e.getCause());
		} catch (FileNotFoundException e) {
			log.error(e.getMessage());
			throw new ExceptionUtil(e.getMessage(),e.getCause());
		}finally{
			try {
				out.flush();
				out.close();
			} catch (IOException e) {
				log.error(e.getMessage());
				throw new ExceptionUtil(e.getMessage(),e.getCause());
			}
		}
    	return sb.toString();
	 }


	/**
	 * 创建分页
	 * @param xtGeneratorTableColumnList
	 * @param xtGenerator
	 * @return
	 */
	public String createWebList(List<XtGeneratorTableColumn> xtGeneratorTableColumnList,XtGenerator xtGenerator) {
		StringBuffer sb = new StringBuffer();
		//添加注释模块
		sb.append("\t/**\r\n");
    	sb.append("\t* 查询并分页\r\n");
    	sb.append("\t* @param baseSearch \r\n");
        sb.append("\t*/\r\n");
        //查询并分页
		sb.append("\t@ApiOperation(value=\"查询并分页\", notes=\"查询并分页\")\r\n");
		sb.append("\t@NeedLoginUnAuth\r\n");
        sb.append("\t@PostMapping(value=\"/list\")\r\n");
    	sb.append("\tpublic BasePage get"+uprepchar(xtGenerator.getXt_generator_tbname())+"ListByCondition(@RequestBody(required=true)BaseSearch baseSearch){\r\n");
		sb.append("\t\tMap<String, Object> condition = baseSearch.convert();\r\n");
		if(xtGenerator.getXt_generator_page().equals("2")){
			//普通分页
			sb.append("\t\tcommonPager(baseSearch);\r\n");
		}else{
			//物理分页
			sb.append("\t\tcommonHPager(baseSearch);\r\n");
		}
    	//子表操作 通过外键查找
    	if(xtGenerator.getIs_one_to_many().equals("1") && !xtGenerator.isIs_main_table()){
//    		sb.append("\t\tcondition.put(\""+xtGenerator.getFk()+"\",request.getParameter(\""+xtGenerator.getFk()+"\"));\r\n");//屏蔽
    	}
		
		sb.append("\t\tList<"+toUpperCase(xtGenerator.getXt_generator_tbname())+"> " +lowfristchar(xtGenerator.getXt_generator_tbname())+"List = "+lowfristchar(xtGenerator.getXt_generator_tbname())+"Service.get"+uprepchar(xtGenerator.getXt_generator_tbname())+"ListByCondition(condition);\r\n");
		if(xtGenerator.getXt_generator_page().equals("2")){
			sb.append("\t\tint total = "+lowfristchar(xtGenerator.getXt_generator_tbname())+"Service.get"+uprepchar(xtGenerator.getXt_generator_tbname())+"ListCountByCondition(condition);\r\n");
			//开发模式0Extjs模式  1bootstrap模式
			if("0".equals(xtGenerator.getKf_mode())){
				sb.append("\t\treturn outPageBootStr("+lowfristchar(xtGenerator.getXt_generator_tbname())+"List,total);\r\n");
			}
			if("1".equals(xtGenerator.getKf_mode())){
				sb.append("\t\treturn outPageBootStr("+lowfristchar(xtGenerator.getXt_generator_tbname())+"List,total);\r\n");
			}
		}else{
			sb.append("\t\tPageInfo<"+toUpperCase(xtGenerator.getXt_generator_tbname())+"> page = new PageInfo<"+toUpperCase(xtGenerator.getXt_generator_tbname())+">(" +lowfristchar(xtGenerator.getXt_generator_tbname())+"List);\r\n");
			
			//开发模式0Extjs模式  1bootstrap模式
			if("0".equals(xtGenerator.getKf_mode())){
				sb.append("\t\treturn outPageStr(page,request);\r\n");	
			}
			if("1".equals(xtGenerator.getKf_mode())){
				sb.append("\t\treturn outPageBootStr(page,baseSearch);\r\n");
			}
		}
		sb.append("\t}\r\n");
		return sb.toString();
	}
	
	/**
	* 查询单个记录
	* @param xtGeneratorTableColumnList
	* @param xtGenerator
	* @return
	*/
	public String createWebObj(List<XtGeneratorTableColumn> xtGeneratorTableColumnList,XtGenerator xtGenerator) {
		StringBuffer sb = new StringBuffer();
		//添加注释模块
		sb.append("\t/**\r\n");
    	sb.append("\t* 查询单条记录\r\n");
    	sb.append("\t* @param "+getColumnKey(xtGeneratorTableColumnList)+" \r\n");
        sb.append("\t*/\r\n");
        //添加方法模块

		sb.append("\t@ApiOperation(value=\"查询单条记录\", notes=\"查询单条记录\")\r\n");
        sb.append("\t@NeedLoginUnAuth\r\n");
        sb.append("\t@GetMapping(value=\"/get/{"+getColumnKey(xtGeneratorTableColumnList)+"}\")\r\n");
        sb.append("\tpublic BaseResult get"+uprepchar(xtGenerator.getXt_generator_tbname())+"ById(@PathVariable(\""+getColumnKey(xtGeneratorTableColumnList)+"\")String "+getColumnKey(xtGeneratorTableColumnList)+"){\r\n");
		sb.append("\t\t"+toUpperCase(xtGenerator.getXt_generator_tbname())+" "+lowfristchar(xtGenerator.getXt_generator_tbname())+" = "+lowfristchar(xtGenerator.getXt_generator_tbname())+"Service.get"+uprepchar(xtGenerator.getXt_generator_tbname())+"ById("+getColumnKey(xtGeneratorTableColumnList)+");\r\n");
		sb.append("\t\treturn outDataStr("+lowfristchar(xtGenerator.getXt_generator_tbname())+");\r\n");
		sb.append("\t}\r\n");
		return sb.toString();
	}
	
	/**
	 * 创建添加
	 * @param xtGeneratorTableColumnList
	 * @param xtGenerator
	 * @return
	 */
	public String createWebAdd(List<XtGeneratorTableColumn> xtGeneratorTableColumnList,XtGenerator xtGenerator) {
		StringBuffer sb = new StringBuffer();
		if(xtGenerator.getIs_one_to_many().equals("1")){
			
		}else{//单表操作
			
		}
		//添加注释模块
		sb.append("\t/**\r\n");
    	sb.append("\t* 添加\r\n");
    	sb.append("\t* @param "+lowfristchar(xtGenerator.getXt_generator_tbname())+" \r\n");
        sb.append("\t*/\r\n");
        //添加方法模块
		sb.append("\t@ApiOperation(value=\"添加\", notes=\"添加\")\r\n");
        sb.append("\t@PostMapping(value=\"/add\")\r\n");
        sb.append("\tpublic BaseResult add"+uprepchar(xtGenerator.getXt_generator_tbname())+"(@RequestBody "+toUpperCase(xtGenerator.getXt_generator_tbname())+" "+lowfristchar(xtGenerator.getXt_generator_tbname())+"){\r\n");
        sb.append("\t\tint i = 0;\r\n");
		//判断对象是否存在
        sb.append("\t\tif(null != "+lowfristchar(xtGenerator.getXt_generator_tbname())+"){\r\n");
        //设置主键
        sb.append("\t\t\t"+lowfristchar(xtGenerator.getXt_generator_tbname())+".set"+getColumnKeyUpOneChar(xtGeneratorTableColumnList)+"(toUUID());\r\n");
        //执行添加操作
        sb.append("\t\t\ti="+lowfristchar(xtGenerator.getXt_generator_tbname())+"Service.add"+uprepchar(xtGenerator.getXt_generator_tbname())+"("+lowfristchar(xtGenerator.getXt_generator_tbname())+");\r\n");
		sb.append("\t\t}\r\n");
		//判断是否操作成功
		sb.append("\t\tif(i>0){\r\n");
//		sb.append("\t\t\toutAudStr(true, \"添加信息成功\");\r\n");
		sb.append("\t\t\treturn outAudStr(true);\r\n");
		sb.append("\t\t}else{\r\n");
//		sb.append("\t\t\toutAudStr(false, \"添加信息失败\");\r\n");
		sb.append("\t\t\treturn outAudStr(false);\r\n");
		sb.append("\t\t}\r\n");
		sb.append("\t}\r\n");
		return sb.toString();
	}
	
	/**
	 * 创建修改
	 * @param xtGeneratorTableColumnList
	 * @param xtGenerator
	 * @return
	 */
	public String createWebUpdate(List<XtGeneratorTableColumn> xtGeneratorTableColumnList,XtGenerator xtGenerator) {
		StringBuffer sb = new StringBuffer();
		//添加注释模块
		sb.append("\t/**\r\n");
    	sb.append("\t* 修改\r\n");
    	sb.append("\t* @param "+lowfristchar(xtGenerator.getXt_generator_tbname())+" \r\n");
        sb.append("\t*/\r\n");
        //修改方法模块
		sb.append("\t@ApiOperation(value=\"修改\", notes=\"修改\")\r\n");
        sb.append("\t@PutMapping(value=\"/update\")\r\n");
        sb.append("\tpublic BaseResult update"+uprepchar(xtGenerator.getXt_generator_tbname())+"(@RequestBody "+toUpperCase(xtGenerator.getXt_generator_tbname())+" "+lowfristchar(xtGenerator.getXt_generator_tbname())+"){\r\n");
        sb.append("\t\tint i = 0;\r\n");
		//判断对象是否存在
        sb.append("\t\tif(null != "+lowfristchar(xtGenerator.getXt_generator_tbname())+"){\r\n");
        //执行添加操作
        sb.append("\t\t\ti="+lowfristchar(xtGenerator.getXt_generator_tbname())+"Service.update"+uprepchar(xtGenerator.getXt_generator_tbname())+"("+lowfristchar(xtGenerator.getXt_generator_tbname())+");\r\n");
		sb.append("\t\t}\r\n");
		//判断是否操作成功
		sb.append("\t\tif(i>0){\r\n");
//		sb.append("\t\t\toutAudStr(true, \"修改信息成功\");\r\n");
		sb.append("\t\t\treturn outAudStr(true);\r\n");
		sb.append("\t\t}else{\r\n");
//		sb.append("\t\t\toutAudStr(false, \"修改信息失败\");\r\n");
		sb.append("\t\t\treturn outAudStr(false);\r\n");
		sb.append("\t\t}\r\n");
		sb.append("\t}\r\n");
		return sb.toString();
	}
	
	/**
	 * 创建删除
	 * @param xtGeneratorTableColumnList
	 * @param xtGenerator
	 * @return
	 */
	public String createWebDel(List<XtGeneratorTableColumn> xtGeneratorTableColumnList,XtGenerator xtGenerator) {
		StringBuffer sb = new StringBuffer();
		//添加注释模块
		sb.append("\t/**\r\n");
    	sb.append("\t* 删除\r\n");
    	sb.append("\t* @param "+getColumnKey(xtGeneratorTableColumnList)+" \r\n");
        sb.append("\t*/\r\n");
        //删除方法模块
		sb.append("\t@ApiOperation(value=\"删除\", notes=\"删除\")\r\n");
        sb.append("\t@DeleteMapping(value=\"/delete\")\r\n");
        sb.append("\tpublic BaseResult del"+uprepchar(xtGenerator.getXt_generator_tbname())+"(String "+getColumnKey(xtGeneratorTableColumnList)+"){\r\n");
		sb.append("\t\tint i = 0;\r\n");
		//判断对象是否存在
        sb.append("\t\tif(!StringUtil.isEmpty("+getColumnKey(xtGeneratorTableColumnList)+")){\r\n");
        //执行添加操作
        sb.append("\t\t\tMap<String, Object> condition = new HashMap<String, Object>();\r\n");
        sb.append("\t\t\tcondition.put(\""+getColumnKey(xtGeneratorTableColumnList)+"\","+getColumnKey(xtGeneratorTableColumnList)+".split(\",\"));\r\n");
        sb.append("\t\t\ti="+lowfristchar(xtGenerator.getXt_generator_tbname())+"Service.del"+uprepchar(xtGenerator.getXt_generator_tbname())+"(condition);\r\n");
		sb.append("\t\t}\r\n");
		//判断是否操作成功
		sb.append("\t\tif(i>0){\r\n");
//		sb.append("\t\t\toutAudStr(true, \"删除信息成功\");\r\n");
		sb.append("\t\t\treturn outAudStr(true);\r\n");
		sb.append("\t\t}else{\r\n");
//		sb.append("\t\t\toutAudStr(false, \"删除信息失败\");\r\n");
		sb.append("\t\t\treturn outAudStr(false);\r\n");
		sb.append("\t\t}\r\n");
		sb.append("\t}\r\n");
		return sb.toString();
	}
}
